<?php
if(!defined("YUEXUAN_REAL_ROOT_PATH")){
	exit("Access Denied.");
}

class userException extends Exception {
	// pass
}

/**
 * 用户管理
 * @author tongjun
 *
 */
class user_user extends base {
	private $userTableName = "#tablePre#user";
	
	// 登录
	public function login($userName, $password){
		$userInfo = $this->findUserByUserName($userName);
		if($userInfo){
			if($userInfo["passwd"]==md5($password)){
				unset($userInfo["passwd"]);
				$_SESSION["userId"] = $userInfo["id"];
				$_SESSION["userInfo"] = $userInfo;
				return true;
			}else{
				throw new Exception("密码不正确");
			}
		}else{
			throw new Exception("此用户不存在");
		}
	}
	
    // 根据用户id读取用户信息
    public function findUserByUserId($userId){
    	$sql = "select * from {$this->userTableName} " .
    			"where id={$userId}";
    	return $this->db(ext_dbHandle::$slaveDbServer)->getRow($sql);
    }
    
    // 根据用户名读取用户信息
    public function findUserByUserName($userName){
    	$sql = "select * from {$this->userTableName} " .
    			"where username='{$userName}'";
    	return $this->db(ext_dbHandle::$slaveDbServer)->getRow($sql);
    }
    
	// 更新用户信息
	public function updateUserInfo($userId, $userInfo){
		$where = array(
			"id" => $userId
		);
		$this->db(ext_dbHandle::$masterDbServer)->update($this->userTableName, $userInfo, $where);
	}
	
	// 更新用户密码
	public function updateUserPassword($userId, $password){
		$userInfo = array(
			"passwd" => md5($password)
		);
		$where = array(
			"id" => $userId
		);
		$this->db(ext_dbHandle::$masterDbServer)->update($this->userTableName, $userInfo, $where);
	}
    
	// 注册新用户
	public function createUser($userName, $password){
		$defaultUserInfo = array(
		);
		$userInfo = array(
			"username" => $userName,
			"passwd" => md5($password),
		);
		$userInfo = array_merge($defaultUserInfo, $userInfo);
		$this->db(ext_dbHandle::$masterDbServer)->insert($this->userTableName, $userInfo);
	}
	
	// 删除用户
	public function removeUser($userId){
		$sql = "delete from {$this->userTableName} " .
				"where id={$userId}";
		$this->db(ext_dbHandle::$masterDbServer)->exc($sql);
	}
}
